import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import request from '@/utils/request';
import service from './service';

// 定义类型
interface Project {
  id: number;
  created_at: string;
  updated_at: string;
  title: string;
  description: string;
  requirements: string;                    // 接口返回字符串格式
  budget: number;
  deadline: string;
  category: string;
  tags: string;                           // 接口返回字符串格式
  status: 'open' | 'in_progress' | 'completed' | 'closed';
  contact_info?: string;
  is_public: boolean;
  view_count: number;
  apply_count: number;
  priority: number;
  location: string;
  skills: string;
  duration: number;
  max_applicants: number;
  current_applicants: number;
  start_date?: string | null;
  end_date?: string | null;
  creator_id: number;
  creator?: {
    id: number;
    username: string;
    email: string;
    role: string;
    company?: string;
    created_at: string;
  };
  applications: Application[];
  matched_users: any[];
  // 前端计算字段
  enterprise?: string;
}

interface Application {
  id: number;
  project_id: number;
  applicant_id: number;
  status: 'pending' | 'accepted' | 'rejected' | 'withdrawn';
  cover_letter: string;
  resume: string;
  portfolio: string;
  apply_date: string;
  applicant?: {
    id: number;
    username: string;
    email: string;
    role: string;
  };
  project?: {
    title: string;
    enterprise: string;
  };
  research_plan?: string;
  expected_time?: number;
  created_at: string;
  review_date?: string;
  review_comment?: string;
}

interface ApplyForm {
  cover_letter: string;
  research_plan: string;
  resume: string;
  portfolio: string;
  motivation: string;
  qualifications: string;
  expected_time: number;
  start_date: string;
  end_date: string;
}

interface MyProject {
  id: number;
  title: string;
  description: string;
  enterprise: string;
  mentor: string;
  startDate: string;
  progress: number;
  status: 'ongoing' | 'completed' | 'pending' | 'problem';
  statusText: string;
}

// 导师相关API - 与student端保持一致的导出方式
export const getProjects = (params?: {
  page?: number;
  size?: number;
  keyword?: string;
  category?: string;
  status?: string;
  budget_min?: number;
  budget_max?: number;
  is_public?: string;
}): Promise<{
  code: number;
  message: string;
  data: Project[];
  total: number;
  page: number;
  size: number;
  pages: number;
  trace_id: string;
}> => {
  return request({
    url: '/projects',
    method: 'get',
    params
  });
};

export const getProjectDetail = (id: number): Promise<{
  code: number;
  message: string;
  data: Project;
  trace_id: string;
}> => {
  return request({
    url: `/projects/${id}`,
    method: 'get'
  });
};

// 搜索课题
export const searchProjects = (params: {
  q: string;
  page?: number;
  size?: number;
  category?: string;
  budget_min?: number;
  budget_max?: number;
}): Promise<{
  code: number;
  message: string;
  data: Project[];
  total: number;
  page: number;
  size: number;
  pages: number;
  trace_id: string;
}> => {
  return request({
    url: '/projects/search',
    method: 'get',
    params
  });
};

// 获取课题分类
export const getProjectCategories = (): Promise<{
  code: number;
  message: string;
  data: {
    name: string;
    count: number;
    avg_budget: number;
  }[];
  trace_id?: string;
}> => {
  return request({
    url: '/api/v1/projects/categories',
    method: 'get'
  });
};

export const createApplication = (data: {
  project_id: number;
  cover_letter: string;
  resume: string;
  portfolio: string;
  research_plan?: string;
  motivation?: string;
  qualifications?: string;
  expected_time?: number;
  start_date?: string;
  end_date?: string;
}) => {
  return service.post('/applications', data);
};

// 获取我的申请列表
export const getMyApplications = (params?: {
  page?: number;
  size?: number;
}) => {
  return service.get('/applications/my', { params });
};

// 获取申请列表（保留原接口用于其他场景）
export const getApplications = (params?: {
  page?: number;
  size?: number;
  status?: string;
}) => {
  return service.get('/applications', { params });
};

export const getApplication = (applicationId: number) => {
  return service.get(`/applications/${applicationId}`);
};

// 更新申请状态
export const updateApplicationStatus = (id: number, status: 'pending' | 'accepted' | 'rejected' | 'withdrawn') => {
  return service.put(`/applications/${id}/status`, { status });
};

export const withdrawApplicationApi = (applicationId: number): Promise<{
  code: number;
  message: string;
  data: null;
  trace_id: string;
}> => {
  return service.delete(`/applications/${applicationId}`);
};

// 获取我的项目
export const getMyProjects = (params?: {
  page?: number;
  size?: number;
}): Promise<{
  code: number;
  message: string;
  data: MyProject[];
  total: number;
  page: number;
  size: number;
  pages: number;
  trace_id: string;
}> => {
  return service.get('/projects/my', { params });
};

// 导师相关状态和数据
const activeTab = ref('topics');

// 课题筛选条件
const topicFilters = reactive({
  keyword: '',
  category: '',
  status: 'open',
  budget_min: undefined as number | undefined,
  budget_max: undefined as number | undefined,
  is_public: ''
});

// 申请状态筛选
const applicationStatus = ref('');

// 分页
const currentPage = ref(1);
const pageSize = ref(12);
const totalTopics = ref(0);

// 课题数据
const topics = ref<Project[]>([]);
// 申请数据
const applications = ref<Application[]>([]);
// 我的项目数据
const myProjects = ref<MyProject[]>([]);

// 对话框状态
const applyDialogVisible = ref(false);
const applicationDetailVisible = ref(false);
const topicDetailVisible = ref(false);
const currentTopic = ref<Project | null>(null);
const currentApplication = ref<Application | null>(null);

// 申请表单
const applyForm = reactive<ApplyForm>({
  cover_letter: '',
  research_plan: '',
  resume: '',
  portfolio: '',
  motivation: '',
  qualifications: '',
  expected_time: 10,
  start_date: '',
  end_date: '',
});

// 表单验证规则
const applyRules = {
  cover_letter: [
    { required: true, message: '请输入申请信', trigger: 'blur' }
  ],
  research_plan: [
    { required: true, message: '请输入研究计划', trigger: 'blur' }
  ],
  portfolio: [
    { required: true, message: '请输入作品集链接', trigger: 'blur' }
  ],
  resume: [
    { required: true, message: '请输入简历链接', trigger: 'blur' }
  ],
  expected_time: [
    { required: true, message: '请输入预期投入时间', trigger: 'blur' }
  ],
  start_date: [
    { required: true, message: '请选择可开始时间', trigger: 'change' }
  ],
  end_date: [
    { required: true, message: '请选择可结束时间', trigger: 'change' }
  ]
};

// 处理requirements数据，确保返回数组格式
const getRequirementsList = (requirements: any): string[] => {
  if (!requirements) return []

  if (Array.isArray(requirements)) {
    return requirements.filter(req => req && req.trim())
  }

  if (typeof requirements === 'string') {
    // 按换行符分割，过滤空行
    return requirements.split('\n').map(req => req.trim()).filter(req => req)
  }

  return []
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    open: 'success',
    in_progress: 'primary',
    completed: 'info',
    closed: 'danger'
  };
  return typeMap[status] || 'info';
};

const getApplicationStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    accepted: 'success',
    rejected: 'danger',
    withdrawn: 'info'
  };
  return typeMap[status] || 'info';
};

const getProjectStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    ongoing: 'primary',
    completed: 'success',
    pending: 'info',
    problem: 'danger'
  };
  return typeMap[status] || 'info';
};

// 格式化状态显示
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    open: '开放中',
    in_progress: '进行中',
    completed: '已完成',
    closed: '已关闭',
    pending: '待审核',
    accepted: '已通过',
    rejected: '已拒绝',
    withdrawn: '已撤回'
  };
  return statusMap[status] || status;
};

const getProjectStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ongoing: '进行中',
    completed: '已完成',
    pending: '待开始',
    problem: '有问题'
  };
  return statusMap[status] || status;
};

// 格式化日期显示
const formatDate = (dateStr: string | Date) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString();
};

// 检查是否已申请该课题
const hasApplied = (projectId: number) => {
  return applications.value.some(app => app.project_id === projectId && app.status !== 'withdrawn');
};

// 获取课题列表
const fetchProjects = async () => {
  try {
    // 确保申请列表已加载，以便正确显示申请状态
    if (applications.value.length === 0) {
      await fetchApplications();
    }

    // 如果有搜索关键词，使用搜索接口
    if (topicFilters.keyword && topicFilters.keyword.trim()) {
      const searchParams = {
        q: topicFilters.keyword.trim(),
        page: currentPage.value,
        size: pageSize.value,
        category: topicFilters.category,
        budget_min: topicFilters.budget_min,
        budget_max: topicFilters.budget_max
      };
      const response = await searchProjects(searchParams);
      topics.value = (response as any).data.map((project: any) => ({
        ...project,
        enterprise: project.enterprise_id?.toString() || '未知企业',
        statusText: formatStatus(project.status),
        requirements: project.requirements ? (Array.isArray(project.requirements) ? project.requirements : project.requirements.split('\n').filter((req: string) => req.trim())) : [],
        duration: project.duration || 3,
        budget: project.budget || 0
      }));
      totalTopics.value = (response as any).total || topics.value.length;
      return;
    }

    // 否则使用普通列表接口
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: topicFilters.keyword,
      category: topicFilters.category,
      status: topicFilters.status,
      budget_min: topicFilters.budget_min,
      budget_max: topicFilters.budget_max,
      is_public: topicFilters.is_public
    };

    const response = await getProjects(params);
    // 根据实际API返回结构：{ code, message, data: [], total, page, size, pages }
    topics.value = (response as any).data.map((project: any) => ({
      ...project,
      enterprise: project.enterprise_id?.toString() || '未知企业',
      statusText: formatStatus(project.status),
      requirements: project.requirements ? (Array.isArray(project.requirements) ? project.requirements : project.requirements.split('\n').filter((req: string) => req.trim())) : [],
      duration: project.duration || 3,
      budget: project.budget || 0
    }));
    totalTopics.value = (response as any).total || topics.value.length;
  } catch (error) {
    ElMessage.error('获取课题列表失败');
    console.error(error);
  }
};

// 获取课题详情
const fetchProjectDetail = async (id: number) => {
  try {
    const response = await getProjectDetail(id);
    currentTopic.value = response.data;
    topicDetailVisible.value = true;
  } catch (error) {
    ElMessage.error('获取课题详情失败');
    console.error(error);
  }
};

// 获取申请列表
const fetchApplications = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    };

    const response = await getMyApplications(params);
    // 根据API文档，返回结构是 { code, message, data: [], total, page, size, pages }
    applications.value = (response as any).data.map((app: any) => ({
      ...app,
      topicTitle: app?.project?.title || '未知课题',
      enterprise: app?.project?.enterprise_id?.toString() || '未知企业',
      applyTime: formatDate(app.apply_date || app.created_at || ''),
      statusText: formatStatus(app.status),
      feedback: app.review_comment || '',
      start_date: formatDate(app.start_date || ''),
      end_date: formatDate(app.end_date || '')
    }));
  } catch (error) {
    ElMessage.error('获取申请列表失败');
    console.error(error);
  }
};

// 获取我的项目
const fetchMyProjects = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    };

    const response = await getMyProjects(params);
    myProjects.value = (response as any).data.map((project: any) => ({
      ...project,
      statusText: getProjectStatusText(project.status),
      startDate: formatDate(project.startDate || project.start_date || '')
    }));
  } catch (error) {
    ElMessage.error('获取我的项目失败');
    console.error(error);
  }
};

// 课题搜索
const handleTopicSearch = () => {
  currentPage.value = 1;
  fetchProjects();
};

// 重置课题筛选条件
const resetTopicFilters = () => {
  topicFilters.keyword = '';
  topicFilters.category = '';
  topicFilters.budget_min = undefined;
  topicFilters.budget_max = undefined;
  topicFilters.is_public = '';
  currentPage.value = 1;
  fetchProjects();
};

// 显示申请对话框
const showApplyDialog = (topic: Project) => {
  currentTopic.value = topic;
  applyDialogVisible.value = true;
  // 重置表单
  applyForm.cover_letter = '';
  applyForm.research_plan = '';
  applyForm.motivation = '';
  applyForm.qualifications = '';
  applyForm.expected_time = 10;
  applyForm.start_date = '';
  applyForm.end_date = '';
  applyForm.portfolio = '';
  applyForm.resume = '';
};

// 显示课题详情
const showTopicDetail = (topic: Project) => {
  fetchProjectDetail(topic.id);
};

// 联系企业
const contactEnterprise = (topic: Project) => {
  if (!topic.creator_id) {
    ElMessage.warning('无法获取企业信息');
    return;
  }

  // 跳转到聊天页面，并传递企业用户ID
  const router = useRouter();
  router.push({
    path: '/chat',
    query: {
      userId: topic.creator_id,
      userName: topic.creator?.username || topic.enterprise || '企业用户',
      topicTitle: topic.title
    }
  });
};

// 提交申请
const submitApplication = async () => {
  try {
    if (!currentTopic.value) return;

    const requestData = {
      project_id: currentTopic.value.id,
      cover_letter: applyForm.cover_letter,
      portfolio: applyForm.portfolio,
      resume: applyForm.resume,
      motivation: applyForm.motivation,
      qualifications: applyForm.qualifications,
      research_plan: applyForm.research_plan,
      expected_time: parseInt(applyForm.expected_time.toString()),
      start_date: applyForm.start_date ? new Date(applyForm.start_date).toISOString() : '',
      end_date: applyForm.end_date ? new Date(applyForm.end_date).toISOString() : ''
    };

    const response = await createApplication(requestData);

    if ((response as any).code === 200) {
      ElMessage.success('申请提交成功！');
      applyDialogVisible.value = false;
      // 刷新申请列表
      await fetchApplications();
      // 切换到申请进度标签页
      activeTab.value = 'applications';
    } else {
      ElMessage.error((response as any).message || '申请提交失败');
    }
  } catch (error) {
    ElMessage.error('申请提交失败，请重试');
    console.error(error);
  }
};

// 查看申请详情
const viewApplicationDetail = async (application: Application) => {
  try {
    const response = await getApplication(application.id);
    // 根据API文档，返回结构是 { code, message, data: {...}, trace_id }
    currentApplication.value = (response as any).data;
    applicationDetailVisible.value = true;
  } catch (error) {
    ElMessage.error('获取申请详情失败');
    console.error(error);
  }
};

// 撤回申请
const withdrawApplication = async (applicationId: number) => {
  try {
    await ElMessageBox.confirm('确定要撤回该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await withdrawApplicationApi(applicationId);

    if (response.code === 200) {
      ElMessage.success('申请撤回成功');
      fetchApplications();
    } else {
      ElMessage.error(response.message || '撤回申请失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      // 处理具体的错误响应
      const errorMessage = error?.response?.data?.message || error?.message || '撤回申请失败';
      ElMessage.error(errorMessage);
      console.error(error);
    }
  }
};

// 查看项目详情
const viewProjectDetail = (project: MyProject) => {
  ElMessage.info(`查看项目 ${project.title} 的详细信息`);
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  if (activeTab.value === 'topics') {
    fetchProjects();
  } else if (activeTab.value === 'applications') {
    fetchApplications();
  } else if (activeTab.value === 'myProjects') {
    fetchMyProjects();
  }
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  if (activeTab.value === 'topics') {
    fetchProjects();
  } else if (activeTab.value === 'applications') {
    fetchApplications();
  } else if (activeTab.value === 'myProjects') {
    fetchMyProjects();
  }
};

const filteredApplications = computed(() => {
  if (!applicationStatus.value) {
    return applications.value;
  }
  return applications.value.filter(app => app.status === applicationStatus.value);
});

const handleCloseApplyDialog = () => {
  applyDialogVisible.value = false;
};

// 监听标签页切换
watch(activeTab, (newVal) => {
  // 切换标签页时重置分页到第一页
  currentPage.value = 1;

  if (newVal === 'topics') {
    fetchProjects();
  } else if (newVal === 'applications') {
    fetchApplications();
  } else if (newVal === 'myProjects') {
    fetchMyProjects();
  }
});

// 监听申请状态筛选
watch(applicationStatus, () => {
  fetchApplications();
});

// onMounted 已移动到 Vue 组件中

// 导出所有需要的内容
export {
  // 状态和数据
  activeTab,
  topicFilters,
  applicationStatus,
  currentPage,
  pageSize,
  totalTopics,
  topics,
  applications,
  myProjects,
  applyDialogVisible,
  applicationDetailVisible,
  topicDetailVisible,
  currentTopic,
  currentApplication,
  applyForm,
  filteredApplications,

  // 方法
  handleCloseApplyDialog,
  getStatusType,
  getApplicationStatusType,
  getProjectStatusType,
  formatStatus,
  formatDate,
  hasApplied,
  handleTopicSearch,
  resetTopicFilters,
  showApplyDialog,
  showTopicDetail,
  contactEnterprise,
  submitApplication,
  viewApplicationDetail,
  withdrawApplication,
  viewProjectDetail,
  handleSizeChange,
  handleCurrentChange,
  getRequirementsList,
  fetchProjects,
  fetchApplications,
  fetchMyProjects,

  // 表单验证规则
  applyRules
};
